<template>
  <div>
    <!-- Header 头部区域 -->
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon name="arrow-left" color="white" size="18" class="goback" @click="$router.back()" />
      <!-- 搜索组件 -->
      <van-search v-model.trim="kw" placeholder="请输入搜索关键词" background="#007BFF" shape="round" ref="searchRef" @input="onInput" />
    </div>

    <!-- 搜索建议 -->
    <div class="sugg-list" v-if="this.kw !==''">
      <div class="sugg-item" v-for="(item, i) in suggestList" :key="i" v-html="item" @click="goResult"></div>
    </div>

    <!-- 搜索历史 -->
    <div class="search-history" v-else>
  <!-- 标题 -->
  <van-cell title="搜索历史">
    <!-- 使用 right-icon 插槽来自定义右侧图标 -->
    <template #right-icon>
      <van-icon name="delete" class="search-icon" @click="history=[]"/>
    </template>
  </van-cell>

  <!-- 历史列表 -->
  <div class="history-list">
    <span class="history-item" v-for="(tag, i) in history" :key="i" @click="$router.push('/search/'+tag)">{{tag}}</span>
  </div>
    </div>

  </div>
</template>

<script>
import { getSuggestList } from '@/api/searchAPI.js'

export default {
  name: 'Search',
  data () {
    return {
      // 搜索关键词
      kw: '',
      // 控制延时器
      timer: null,
      // 存放搜索建议的空数组
      suggestList: [],
      // 搜索建议
      history: JSON.parse(localStorage.getItem('history') || '[]')
    }
  },
  mounted () {
    // 在进入页面并且页面组件dom元素挂载完毕之后，让input搜索框自动进入焦点
    this.$refs.searchRef && this.$refs.searchRef.querySelector('input').focus()
  },
  methods: {
    onInput () {
      // 防抖2，清空
      clearTimeout(this.timer)
      if (this.kw === '') {
        this.suggestList = []
        return
      }
      // 防抖1，设置延时器
      this.timer = setTimeout(() => {
        // 调用，请求搜索建议的函数
        this.initSuggestList()
      }, 800)
    },
    // 封装，设置请求搜索建议的函数
    async initSuggestList () {
      const { data: res } = await getSuggestList(this.kw)
      if (res.message === 'OK') {
        this.highLight(res.data.options)
        this.suggestList = res.data.options
        // 历史记录
        // 将之前搜索过的内容进行过滤，形成新的数组
        const newArr = this.history.filter(item => item !== this.kw)
        // 对新数组进行头部添加新的纪录
        newArr.unshift(this.kw)
        // 赋值给历史记录展示
        this.history = newArr
      }
    },
    highLight (val) {
      const reg = RegExp(this.kw, 'ig')
      val.forEach((item, index) => {
        val[index] = item.replace(reg, (x) => {
          return `<span style='color: red;font-weight: 800;'>${x}</span>`
        })
      })
    },
    goResult (e) {
      const text = e.currentTarget.innerText
      this.$router.push('/search/' + text)
    }
  },
  watch: {
    history (newValue) {
      localStorage.setItem('history', JSON.stringify(newValue))
    }
  }
}

</script>

<style lang="less" scoped>
.search-header {
  height: 46px;
  display: flex;
  align-items: center;
  background-color: #007bff;
  overflow: hidden;
  // 后退按钮
  .goback {
    padding-left: 14px;
  }
  // 搜索组件
  .van-search {
    flex: 1;
  }
}
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}

</style>
